//
//  SISSMapViewController.m
//  SISSAPP
//
//  Created by 优房网 on 2017/3/14.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSMapViewController.h"
//#import <BaiduMapAPI_Map/BMKMapView.h>
#import <BaiduMapAPI_Base/BMKBaseComponent.h>//引入base相关所有的头文件
#import <BaiduMapAPI_Map/BMKMapComponent.h>//引入地图功能所有的头文件
//#import <BaiduMapAPI_Location/BMKLocationComponent.h>//引入定位功能所有的头文件
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>//引入计算工具所有的头文件
#import "SISSRoundAnnotation.h"
#import "SISSRoundAnnotationView.h"
#import "SISSMessageAnnotationView.h"
#import "SISSMapAreaModel.h"
#import "SISSButton.h"
#import "SISSMapShowViewController.h"

#import "SISSMapManager.h"
#import "SISSMapViewController+InitUI.h"
#import "SISSMapViewController+DataRequest.h"
#import "SISSComboBoxView.h"

@interface SISSMapViewController ()<SISSMapShowViewControllerDelegate>

/// 记录点击过的大头针。便于点击空白时。把这个大头针缩小为原始大小
@property(nonatomic, strong) SISSMessageAnnotationView *messageA;

// 大区大头针数组
@property (nonatomic, strong) NSMutableArray *areaArr;
// 小区大头针数组
@property (nonatomic, strong) NSMutableArray *zoneArr;

/// 数据
@property(nonatomic, copy) NSArray *areaDataSourceArray;
/// 筛选后的数据结构
@property(nonatomic, strong) NSMutableArray *filterStatusSource;


@end

@implementation SISSMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.mapShowType = SISSMapShowTypeHouse;
    
    [self requestData];
    
    // segmentControl
    UISegmentedControl *segmentControl = [[UISegmentedControl alloc] initWithItems:@[@"房源", @"客源", @"出租", @"租客"]];
    segmentControl.selectedSegmentIndex = 0;
    segmentControl.tintColor = COLOR(0x249DC5);
    [segmentControl addTarget:self action:@selector(segmentControlbutClick:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = segmentControl;

    [self setupUI];
    [self locationPrivilege];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recommendedSucces:) name:@"recommendedSuccessNotification" object:nil];
}

- (void)recommendedSucces:(NSNotification *)notification {
    [self requestData];
    [self requestShowDataWithRegion:self.region regionDetail:self.regionDetail];
    
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - SISSComboBoxViewDelegate
- (void)comboBoxViewDidSelectDisplayTypeNormalWithRootItemTitle:(NSString *)rootItemTitle title:(NSString *)title {
    
    if ([rootItemTitle isEqualToString:@"售价"] || [rootItemTitle isEqualToString:@"预算"] || [rootItemTitle isEqualToString:@"租金"] || [rootItemTitle isEqualToString:@"租金预算"]) {
        self.price = title;
    } else if ([rootItemTitle isEqualToString:@"户型"] || [rootItemTitle isEqualToString:@"意向户型"]) {
        self.houseType = title;
    }
    kSISSRefresh.refreshType = SISSRefressTypeUpDown;
    [self requestData];
    [self requestShowDataWithRegion:self.region regionDetail:self.regionDetail];
    
}

- (void)comboBoxViewDidSelectDisplayTypeMultilayerWithRootItemTitle:(NSString *)rootItemTitle title:(NSString *)title subtitle:(NSString *)subtitle {
    
    self.region = title;
    self.regionDetail = subtitle;
    kSISSRefresh.refreshType = SISSRefressTypeUpDown;
    //创建编码对象
    [SISSMapManager disposeGeocoderWithMapVC:self zoomValue:17];
    [self requestData];
    [self requestShowDataWithRegion:self.region regionDetail:self.regionDetail];
    
}

- (void)comboBoxViewDidSelectDisplayTypeFiltersWithTitle:(NSString *)title subtitles:(NSArray *)subtitles {
    
    if ([title isEqualToString:@"可见范围"]) {
        self.visibleRange = 2;
    } else if ([title isEqualToString:@"面积"]) {
        self.area = subtitles;
    } else if ([title isEqualToString:@"朝向"]) {
        self.direction = subtitles;
    } else if ([title isEqualToString:@"装修程度"]) {
        self.decoration = subtitles;
    }
}

- (void)comboBoxViewDidSelectDisplayTypeMultiThreelayersWithRootItemTitle:(NSString *)rootItemTitle firstTitle:(NSString *)firstTitle secondTitle:(NSString *)secondTitle thirdTitle:(NSString *)thirdTitle {
    
}

- (void)comboBoxViewDisplayTypeFiltersConfirmClickAction {
    
    kSISSRefresh.refreshType = SISSRefressTypeUpDown;
    [self requestData];
    [self requestShowDataWithRegion:self.region regionDetail:self.regionDetail];
    self.visibleRange = 1;
    self.area = @[];
    self.direction = @[];
    self.decoration = @[];
}


#pragma mark -- BMKMapViewDelegate
- (void)mapView:(BMKMapView *)mapView regionWillChangeAnimated:(BOOL)animated {
    self.zoomValue = mapView.zoomLevel;
    self.oldCoor = mapView.centerCoordinate;
    NSLog(@"之前的比例尺：%f",mapView.zoomLevel);

}

- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
    
    NSLog(@"更改了区域");
    NSLog(@"当前比例尺%f，过去比例尺：%f",mapView.zoomLevel,self.zoomValue);
    if (mapView.zoomLevel > self.zoomValue) {
        NSLog(@"地图放大了");
    }else if (mapView.zoomLevel < self.zoomValue){
        NSLog(@"地图缩小了");
    }
    [mapView removeAnnotations:self.areaArr];
    [mapView removeAnnotations:self.zoneArr];

    [self loadDataWithZoomLevel:mapView.zoomLevel];
}

- (void)loadDataWithZoomLevel:(NSInteger)zoomLevel {
    WeakSelf

    if (zoomLevel > 13) { // 请求小区
        NSInteger count = 0;
        switch (self.mapShowType) {
            case SISSMapShowTypeHouse: {
                count = self.houseMapRegionDetailArr.count;
            }
                break;
            case SISSMapShowTypePassenger: {
                count = self.passengerMapRegionDetailArr.count;
            }
                break;
            case SISSMapShowTypeRentOut: {
                count = self.rentOutMapRegionDetailArr.count;
            }
                break;
            case SISSMapShowTypeTenant: {
                count = self.tenantMapRegionDetailArr.count;
            }
                break;
                
            default:
                break;
        }
    
        for (NSInteger i = 0; i < count; i++) {
            
            SISSRoundAnnotation *an = [[SISSRoundAnnotation alloc] init];
            CLLocationCoordinate2D coor;
            SISSMapAreaModel *model;
            
            switch (self.mapShowType) {
                case SISSMapShowTypeHouse: {
                    model = self.houseMapRegionDetailArr[i];
                }
                    break;
                case SISSMapShowTypePassenger: {
                    model = self.passengerMapRegionDetailArr[i];
                }
                    break;
                case SISSMapShowTypeRentOut: {
                    model = self.rentOutMapRegionDetailArr[i];
                }
                    break;
                case SISSMapShowTypeTenant: {
                    model = self.tenantMapRegionDetailArr[i];
                }
                    break;
                    
                default:
                    break;
            }
            coor.latitude = model.latitude;
            coor.longitude = model.longitude;
            an.type = model.region_type;
            an.coordinate = coor;
            NSString *title = [NSString stringWithFormat:@"%@ %zd",model.region,model.count];
            an.title = title;
            an.Id = model.region;
            
            [weakSelf.zoneArr addObject:an];
            [weakSelf.mapView addAnnotation:an];
        }
    } else { // 请求大区
        NSInteger count = 0;
        switch (self.mapShowType) {
            case SISSMapShowTypeHouse: {
                count = self.houseMapRegionArr.count;
            }
                break;
            case SISSMapShowTypePassenger: {
                count = self.passengerMapRegionArr.count;
            }
                break;
            case SISSMapShowTypeRentOut: {
                count = self.rentOutMapRegionArr.count;
            }
                break;
            case SISSMapShowTypeTenant: {
                count = self.tenantMapRegionArr.count;
            }
                break;
                
            default:
                break;
        }
        
        for (NSInteger i = 0; i < count; i++) {
            SISSRoundAnnotation *an = [[SISSRoundAnnotation alloc] init];
            CLLocationCoordinate2D coor;
            SISSMapAreaModel *model;
            switch (self.mapShowType) {
                case SISSMapShowTypeHouse: {
                    model = self.houseMapRegionArr[i];
                }
                    break;
                case SISSMapShowTypePassenger: {
                    model = self.passengerMapRegionArr[i];
                }
                    break;
                case SISSMapShowTypeRentOut: {
                    model = self.rentOutMapRegionArr[i];
                }
                    break;
                case SISSMapShowTypeTenant: {
                    model = self.tenantMapRegionArr[i];
                }
                    break;
                    
                default:
                    break;
            }
            coor.latitude = model.latitude;
            coor.longitude = model.longitude;
            an.type = model.region_type;
            an.coordinate = coor;
            NSString *countStr = [NSString stringWithFormat:@"%zd",model.count];
            an.title = model.region;
            an.subtitle = countStr;
            an.Id = model.region;
            
            [weakSelf.areaArr addObject:an];
            [weakSelf.mapView addAnnotation:an];
        }
    }
}

// 使用苹果原生库计算两个经纬度直接的距离
- (double)distanceBetweenFromCoor:(CLLocationCoordinate2D)coor1 toCoor:(CLLocationCoordinate2D)coor2 {
    CLLocation *curLocation = [[CLLocation alloc] initWithLatitude:coor1.latitude longitude:coor1.longitude];
    CLLocation *otherLocation = [[CLLocation alloc] initWithLatitude:coor2.latitude longitude:coor2.longitude];
    double distance  = [curLocation distanceFromLocation:otherLocation];
    return distance;
}



// 点击了大头针
- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view {
    if (view.annotation.coordinate.latitude == self.userLocation.location.coordinate.latitude) { // 个人位置特殊处理，否则类型不匹配崩溃
        NSLog(@"点击了个人位置");
        return;
    }
    SISSRoundAnnotation *annotationView = (SISSRoundAnnotation *)view.annotation;
    
    if (annotationView.type == 2) {
        
        SISSMessageAnnotationView *messageAnno = (SISSMessageAnnotationView *)view;
        
        NSString *regionDetailStr = [messageAnno.title componentsSeparatedByString:@" "].firstObject;
//        SISSRoundAnnotationView *roundAnno = (SISSRoundAnnotationView *)view;
        self.regionDetail = regionDetailStr;
        if (self.mapShowType == SISSMapShowTypeHouse) {
            [self.houseFilterView.comBoBoxView.dropDownBoxArray.firstObject updateTitleContent:regionDetailStr];
        } else if (self.mapShowType == SISSMapShowTypePassenger) {
            [self.passengerFilterView.comBoBoxView.dropDownBoxArray.firstObject updateTitleContent:regionDetailStr];
        } else if (self.mapShowType == SISSMapShowTypeRentOut) {
            [self.rentOutFilterView.comBoBoxView.dropDownBoxArray.firstObject updateTitleContent:regionDetailStr];
        } else if (self.mapShowType == SISSMapShowTypeTenant) {
            [self.tenantFilterView.comBoBoxView.dropDownBoxArray.firstObject updateTitleContent:regionDetailStr];
        }
        [self.mapView setMapCenterToScreenPt:CGPointMake(SCREEN_WIDTH * 0.5, SCREEN_HEIGHT * 0.35)];
        [self.mapView setCenterCoordinate:annotationView.coordinate animated:YES];
        
        self.mapShowViewController.area = regionDetailStr;
        [self requestShowDataWithRegion:@"" regionDetail:regionDetailStr];
        
        [self.mapShowViewController.view mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(SCREEN_HEIGHT * 0.5);
        }];
        [UIView animateWithDuration:0.25 animations:^{
            
            [self.view layoutIfNeeded];
        }];

        // 让点击的大头针放大效果
        [messageAnno didSelectedAnnotation:messageAnno];
        
        self.messageA = messageAnno;
        annotationView.messageAnnoIsBig = @"yes";
        // 取消大头针的选中状态，否则下次再点击同一个则无法响应事件
        [mapView deselectAnnotation:annotationView animated:NO];
        // 计算距离 --> 请求列表数据 --> 完成 --> 展示表格
        //  self.communityId = annotationView.Id;
        
    } else {
        
        SISSRoundAnnotationView *roundAnno = (SISSRoundAnnotationView *)view;
        self.region = roundAnno.title;
        if (self.mapShowType == SISSMapShowTypeHouse) {
            [self.houseFilterView.comBoBoxView.dropDownBoxArray.firstObject updateTitleContent:roundAnno.title];
        } else if (self.mapShowType == SISSMapShowTypePassenger) {
            [self.passengerFilterView.comBoBoxView.dropDownBoxArray.firstObject updateTitleContent:roundAnno.title];
        } else if (self.mapShowType == SISSMapShowTypeRentOut) {
            [self.rentOutFilterView.comBoBoxView.dropDownBoxArray.firstObject updateTitleContent:roundAnno.title];
        } else if (self.mapShowType == SISSMapShowTypeTenant) {
            [self.tenantFilterView.comBoBoxView.dropDownBoxArray.firstObject updateTitleContent:roundAnno.title];
        }
        // 点击了区域--->进入小区
        // 拿到大头针经纬度，放大地图。然后重新计算小区
        [mapView setCenterCoordinate:annotationView.coordinate animated:NO];
        [mapView setZoomLevel:15];
    }
}
- (void)mapView:(BMKMapView *)mapView didDeselectAnnotationView:(BMKAnnotationView *)view {
    
    if (view.annotation.coordinate.latitude == self.userLocation.location.coordinate.latitude) { // 个人位置特殊处理，否则类型不匹配崩溃
        NSLog(@"点击了个人位置");
        return;
    }
    
    SISSRoundAnnotation *annotationView = (SISSRoundAnnotation *)view.annotation;
    if (annotationView.type == 2) {
        SISSMessageAnnotationView *messageAnno = (SISSMessageAnnotationView *)view;
        annotationView.messageAnnoIsBig = @"yes";
        [messageAnno didDeSelectedAnnotation:messageAnno];
        [mapView mapForceRefresh];
    }
}

#pragma mark - SISSMapShowViewControllerDelegate
- (void)shrinkButtonClickAction {
    
    [self.mapShowViewController.view mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(SCREEN_HEIGHT);
    }];
    
    [UIView animateWithDuration:0.25 animations:^{
        
        [self.mapView setMapCenterToScreenPt:CGPointMake(SCREEN_WIDTH * 0.5, SCREEN_HEIGHT * 0.5)];
        
        [self.view layoutIfNeeded];
    }];
}


#pragma mark - segmentControl点击事件
- (void)segmentControlbutClick:(UISegmentedControl *)sender {
    
    self.houseFilterView.hidden = sender.selectedSegmentIndex != 0;
    self.passengerFilterView.hidden = sender.selectedSegmentIndex != 1;
    self.rentOutFilterView.hidden = sender.selectedSegmentIndex != 2;
    self.tenantFilterView.hidden = sender.selectedSegmentIndex != 3;
    [self.houseFilterView.comBoBoxView dismissPopView];
    [self.passengerFilterView.comBoBoxView dismissPopView];
    [self.rentOutFilterView.comBoBoxView dismissPopView];
    [self.tenantFilterView.comBoBoxView dismissPopView];
    
    if (sender.selectedSegmentIndex == 0) {
        
        self.mapShowType = SISSMapShowTypeHouse;
    } else if (sender.selectedSegmentIndex == 1) {
       
       self.mapShowType = SISSMapShowTypePassenger;
    } else if (sender.selectedSegmentIndex == 2) {
        
        self.mapShowType = SISSMapShowTypeRentOut;
    } else if (sender.selectedSegmentIndex == 3) {
        
        self.mapShowType = SISSMapShowTypeTenant;
    }
    self.region = @"不限";
    self.regionDetail = @"";
    [self requestData];
    
    //
    [self.mapShowViewController.view mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(SCREEN_HEIGHT);
    }];
    
    [UIView animateWithDuration:0.25 animations:^{
        
        [self.mapView setMapCenterToScreenPt:CGPointMake(SCREEN_WIDTH * 0.5, SCREEN_HEIGHT * 0.5)];
        
        [self.view layoutIfNeeded];
    }];
    
    [self.mapView setZoomLevel:13];
    [self mapView:self.mapView regionDidChangeAnimated:YES];
}


#pragma mark - Getter & Setter
- (NSArray *)areaDataSourceArray {
    if (!_areaDataSourceArray) {
        _areaDataSourceArray = [SISSMapAreaModel loadMapAreaData];
    }
    return _areaDataSourceArray;
}

- (NSMutableArray *)zoneArr {
    if (!_zoneArr) {
        _zoneArr = [NSMutableArray array];
    }
    return _zoneArr;
}

- (NSMutableArray *)areaArr {
    if (!_areaArr) {
        _areaArr = [NSMutableArray array];
    }
    return _areaArr;
}

- (SISSMapShowViewController *)mapShowViewController {
    if (!_mapShowViewController) {
        _mapShowViewController = [[SISSMapShowViewController alloc] init];
        [self addChildViewController:_mapShowViewController];
        [_mapShowViewController didMoveToParentViewController:self];
        _mapShowViewController.delegate = self;
    }
    return _mapShowViewController;
}

- (NSArray *)area {
    if (_area == nil) {
        _area = [NSArray array];
    }
    return _area;
}

- (NSArray *)direction {
    if (_direction == nil) {
        _direction = [NSArray array];
    }
    return _direction;
}

- (NSArray *)decoration {
    if (_decoration == nil) {
        _decoration = [NSArray array];
    }
    return _decoration;
}

@end
